#!/usr/bin/env python
"""
Parses the dmq config file and start/stop/restarts
dmq processes for the system.
"""
import os
import sys
from optparse import OptionParser
import ConfigParser

import logging
logging.basicConfig(level=logging.DEBUG,
    format='%(asctime)s %(levelname)s %(message)s')

THIS_DIR = os.path.dirname(os.path.realpath(__file__))
dmq_dir = os.path.realpath(os.path.join(THIS_DIR, '../'))
if dmq_dir not in sys.path:
    sys.path.append(dmq_dir)


import dmq.log as log
from dmqmaster import DMQMaster
import dlibs


def path_resolve(path):
    """docstring for path_resolve"""

    if path[0] != '/':
        THIS_DIR = os.path.dirname(os.path.realpath(__file__))
        return os.path.normpath("%s/%s" % (THIS_DIR, path))

    return os.path.normpath(path)
#path_resolve()


def main():

    opt_parser = OptionParser(
        usage="usage: %prog [options] start|stop|restart")
    opt_parser.add_option("-c", "--config", dest="config_file",
                          default="/etc/dmq/dmq.ini",
                          help=("The path to the config .ini file for this"
                                " Django-dmq instance"))
    opt_parser.add_option("-s", "--single", dest="single",
                          action="store_true", default=False,
                          help=("Run the Django-dmq service as a single"
                                " instance."
                                " No worker processes will be forked and no "
                                " routing devices"
                                " will be created to manage internal"
                                " connections."
                                " This option will override the 'workers'"
                                " option in the configuration file"))
    opt_parser.add_option("-d", "--daemonize", dest="daemonize",
                          action="store_true", default=False,
                          help=("Have the Django-dmq service daemonize itself"
                                " and run in the background."
                                " It's best to have a service controler, like"
                                " systemd, daemonize and manage "
                                " the dmq process for you. But dmq does know"
                                " how to daemonize and manage itself"
                                " if you prefer to not configure dmq under"
                                " your init system."
                                " This option will override the 'deamonize'"
                                " option in the configutation file"))
    opt_parser.add_option("-z", "--whocaresabountzombies",
                          dest="whocaresabountzombies", action="store_true",
                          default=False,
                          help=("If a pid file exists normaly Django-dmq will"
                                " not run."
                                " If the -z, --whocaresabountzombies option is"
                                " given, the existing pid file will be"
                                " This option will override the 'deamonize'"
                                " option in the configutation file. "
                                " over written and the server will be started,"
                                " zombies or not."))

    (options, args) = opt_parser.parse_args()
    if len(args) < 1 or args[:1][0] not in ('start', 'stop', 'restart'):
        print("You must specify an action")
        opt_parser.print_help()
        sys.exit(1)

    action = args[:1][0]
    cfgpath = options.config_file

    try:
        cfg = dlibs.get_cfg(cfgpath)
        cfg_section = "DEFAULT"

        unix_socket_dir = cfg.get(cfg_section, 'unix_socket_dir')

        log_dir = path_resolve(cfg.get(cfg_section, 'log_dir'))
        log_file = cfg.get(cfg_section, 'log_file')
        log_level = cfg.get(cfg_section, 'log_level')
        print("Starting logger.\n\tlog_dir:%s\n\tlog_file:%s\n\tlog_level:%s" %
              (log_dir, log_file, log_level))
        if not os.path.isdir(log_dir):
            os.mkdir(log_dir)

        log.start_logger(log_dir, log_file, log_level)

        pid_dir = path_resolve(cfg.get(cfg_section, 'pid_dir'))
        pid_file = cfg.get(cfg_section, 'pid_file')
        pidfile = "%s/%s" % (pid_dir, pid_file)

        if not os.path.isdir(pid_dir):
            os.mkdir(pid_dir)

        # If the pid file exists, that means there was
        # an unclean exit. Alert the user, and unless
        # the user explicity telles us to over write the
        # existing pid file, we exit.
        if os.path.isfile(pid_file):
            print(("The pid file %s already exists!!! There are likely zombies"
                   " roaming about you need to clean up."))
            if not options.whocaresabountzombies:
                sys.exit(3)

        dmq_user = cfg.get(cfg_section, 'user')
        dmq_group = cfg.get(cfg_section, 'group')

        zmq_admin_host = cfg.get(cfg_section, 'zmq_admin_host')
        zmq_admin_port = cfg.getint(cfg_section, 'zmq_admin_port')
        zmq_admin_transport = cfg.get(cfg_section, 'zmq_admin_transport')

        num_workers = 1
        if cfg.has_option(cfg_section, 'workers'):
            num_workers = cfg.getint(cfg_section, 'workers')
        else:
            num_workers = dlibs.cpu_count()
            log.log(("No 'workers' option specified in the config file,"
                     " starting %d workers") % (num_workers,), 'info')

        app_settings_file = path_resolve(
            cfg.get(cfg_section, 'app_settings_file'))

        fio = {
            'stdin': cfg.get(cfg_section, 'stdin'),
            'stdout': cfg.get(cfg_section, 'stdout'),
            'stderr': cfg.get(cfg_section, 'stderr')
        }

        zmq_admin = {
            'host': zmq_admin_host,
            'transport': zmq_admin_transport,
            'port': zmq_admin_port,
        }

        daemonize = cfg.getboolean(
            cfg_section, 'daemonize') or options.daemonize

        whocaresabountzombies = cfg.getboolean(
            cfg_section,
            'whocaresabountzombies') or options.whocaresabountzombies

        single = cfg.getboolean(cfg_section, 'single') or options.single

        dargs = (dmq_user, dmq_group, pidfile, app_settings_file)
        dkwargs = {
            'workers': num_workers,
            'daemonize': daemonize,
            'zmq_admin': zmq_admin,
            'fio': fio,
            'single_proc': single,
            'daemonize': daemonize,
            'whocaresabountzombies': whocaresabountzombies,
            'unix_socket_dir': unix_socket_dir,
        }

        log.log("dmq dargs : %s" % (dargs,), 'debug')
        log.log("dmq dkwargs : %s" % (dkwargs,), 'debug')

        dmqm = DMQMaster(*dargs, **dkwargs)
        if 'start' == action:
            log.log("starting dmq", 'info')
            dmqm.start()
        elif 'stop' == action:
            log.log("stoping dmq", 'info')
            dmqm.stop()
        elif 'restart' == action:
            log.log("restarting dmq", 'info')
            dmqm.stop()
            dmqm.start()
        else:
            opt_parser.print_usage()

    except Exception as e:
        log.log("main: pokemon exception: %s" % e, 'critical')
        import traceback
        traceback.print_exc(e)
        raise

    log.log("dmq main is exiting", 'debug')
    sys.exit(0)
#main()

#----------------------------------------------------------------------------
# Main
#----------------------------------------------------------------------------

if __name__ == "__main__":
    main()

# vim:ft=python
